<template>
  <div>
    <el-card header="角色列表">
      <!--<MForm :fields="fields" @submit="search" @cancel="search"> </MForm>-->
      <MTable
        :columns="columns"
        :http="roleList"
        :params="params"
        v-model:isReload="isReload"
        v-model:selectKeys="selectKeys"
        height="calc(100vh - 370px)"
        rowKey="id"
        :series="true"
      >
        <template #extra>
          <el-button type="primary" @click="edit(0)">新增</el-button>
          <!--<MDeleteButton-->
          <!--  :selectKeys="selectKeys"-->
          <!--  @click="del(selectKeys)"-->
          <!--&gt;</MDeleteButton>-->
        </template>

        <template #actions="{ row }">
          <MA type="primary" @click="edit(row.id)">编辑</MA>
          <MA type="danger" @click="del(row.id)">删除</MA>
        </template>
      </MTable>
    </el-card>
    <MFormDialog
      v-model="formDialog.visible"
      v-bind="formDialog"
      :value="form"
      :fields="dialogFields"
      :httpAdd="roleAdd"
      :httpEdit="roleEdit"
      :httpGet="roleDetail"
      @reload="reload"
      :getHandler="getHandler"
    ></MFormDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { columns, fields, dialogFields } from './config'
import {
  roleList,
  roleAdd,
  roleDetail,
  roleEdit,
  roleDel
} from '@/api/system/role/role.ts'
import { menuList } from '@/api/system/menu/menu.ts'

onMounted(() => {
  menuList().then((res) => {
    dialogFields.value.forEach((item) => {
      if (item.key === 'menu_ids') {
        item.attrs.data = res
      }
    })
  })
})

const getHandler = e => {
  console.log('e', e)
  e.menu_ids = e.menus.map((item: any) => item.id)
  return e
}

// 搜索
const params = ref<any>({})
const search = (data: any) => {
  params.value = {
    ...params.value,
    ...data
  }
}

const selectKeys = ref<number[]>([])

// 重载
const isReload = ref(true)
const reload = () => {
  isReload.value = true
}

const form = ref<{ parent_id: number | undefined }>({
  parent_id: undefined
})

// 新增/编辑
const formDialog = reactive({
  visible: false,
  id: 0
})
const edit = (id: number) => {
  if (id == 0) {
    form.value.parent_id = undefined
  }
  formDialog.id = id
  formDialog.visible = true
}

// 删除
const del = (id: number) => {
  roleDel(id).then(() => {
    ElMessage.success('删除成功')
    reload()
  })
}
</script>

<style lang="scss" scoped></style>
